package com.niiwoo.civet.trade.service.local.third;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.enums.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.alibaba.fastjson.JSONObject;
import com.niiwoo.activity.event.enums.ProjectSubStatusEventEnum;
import com.niiwoo.asset.cardniu.dto.mq.CardNiuExternalMQConstants;
import com.niiwoo.asset.cardniu.dto.request.LoanStatusDTO;
import com.niiwoo.asset.constant.MqConstants;
import com.niiwoo.asset.dto.mq.RepaymentResultDTO;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

/**
 * Created by yuanguang on 2018/1/31.
 */
@Service
@Slf4j
public class NotifyAssetLocalService {
    @Autowired
    private ProjectMapperExt projectMapperExt;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 标的结清通知资产端
     * @param projectId
     * @param subStatusEventEnum
     */
    public void sendProjectStatusChangeEvent(Long projectId, byte status, ProjectSubStatusEventEnum subStatusEventEnum) {
        try {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    super.afterCommit();
                    Project project = projectMapperExt.selectByPrimaryKey(projectId);
                    if(project==null){
                        return;
                    }
                    LoanStatusDTO loanStatusDTO = new LoanStatusDTO();
                    loanStatusDTO.setType(project.getType());
                    loanStatusDTO.setProjectId(projectId);
                    loanStatusDTO.setStatus(status);
                    loanStatusDTO.setSubStatus(subStatusEventEnum.getSubStatus());//ProjectSubStatusEnum.COLLECTING_INIT.getSubStatus()
                    log.info("还款事务已提交，标的状态变更事件发送（给资产端）,LoanStatusDTO={}", JSONObject.toJSONString(loanStatusDTO));
                    rabbitTemplate.convertAndSend(CardNiuExternalMQConstants.Exchange.LOAN_STATUS_EXCHANGE,
                            CardNiuExternalMQConstants.getRoutingKey(CardNiuExternalMQConstants.Exchange.LOAN_STATUS_EXCHANGE,CardNiuExternalMQConstants.Queue.LOAN_STATUS_QUEUE), loanStatusDTO);
                }
            });
        } catch (Exception e) {
            log.error("send to asset projectStatusChangeEvent failed.", e);
        }
    }

    /**
     * 发送逾期消息到卡牛
     * @param projectId
     */
    public void sendOverDueMsgToAssert(Long projectId){
        try {
            Project project = projectMapperExt.selectByPrimaryKey(projectId);
            if (project != null && project.getFromSource() == ProjectFromSourceEnum.CARD_NIU.getType().byteValue()) {
                LoanStatusDTO loanStatusDTO = new LoanStatusDTO();
                loanStatusDTO.setProjectId(projectId);
                loanStatusDTO.setStatus(ProjectStatusEnum.REPAYING.getStatus());
                loanStatusDTO.setSubStatus(ProjectSubStatusEnum.REPAYING_OVERDUE.getSubStatus());
                loanStatusDTO.setType(com.niiwoo.civet.trade.enums.ProjectTypeEnum.CARD_NIU_LOAN.getValue());
                log.info("sendOverDueMsgToAssert LoanStatusDTO:{}", JSON.toJSON(loanStatusDTO));
                rabbitTemplate.convertAndSend(CardNiuExternalMQConstants.Exchange.LOAN_STATUS_EXCHANGE,
                        CardNiuExternalMQConstants.getRoutingKey(CardNiuExternalMQConstants.Exchange.LOAN_STATUS_EXCHANGE, CardNiuExternalMQConstants.Queue.LOAN_STATUS_QUEUE), loanStatusDTO);
            }
        } catch (Exception e) {
            log.error("sendOverDueMsgToAssert LoanStatusDTO异常 projectId:{}", projectId, e);
        }
    }
}
